<template>
  <div class="content">
    <div class="elTable">
      <!-- 表格 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          v-for="tab in tabs"
          :key="tab.label"
          :label="tab.label"
          :name="tab.label"
        >
          <div class="tabInfo">
            <div class="search">
              <SearchForm
                :formObj="formObj"
                :formData="searchForm"
                :tip="tip"
              />
            </div>
            <el-table :data="onboardingTableData" style="width: 100%">
              <el-table-column type="index" label="序号" width="60" />
              <template v-for="col in column" :key="col.prop">
                <!-- 普通数据列 -->
                <el-table-column
                  v-if="col.dataType !== 'option'"
                  :prop="col.prop"
                  :label="col.label"
                  :width="col.width"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <!-- 性别列 -->
                    <template v-if="col.prop === 'sex'">
                      {{ scope.row.sex === 0 ? "男" : "女" }}
                    </template>
                    <!-- 部门列 -->
                    <template v-else-if="col.prop === 'deptId'">
                      {{ setDeptName(scope.row.deptId) }}
                    </template>
                    <!-- 创建人列 -->
                    <template v-else-if="col.prop === 'createId'">
                      {{ setName(scope.row.createId) }}
                    </template>
                    <!-- 状态列 -->
                    <template v-else-if="col.prop === 'status'">
                      {{ formatStatus(scope.row.status) }}
                    </template>
                    <!-- 普通文本列 -->
                    <template v-else>
                      {{ scope.row[col.prop] }}
                    </template>
                  </template>
                </el-table-column>
                <!-- 操作列 -->
                <el-table-column
                  v-else
                  :label="col.label"
                  :width="col.width"
                  fixed="right"
                >
                  <template #default="scope">
                    <el-button
                      v-for="(btn, index) in col.operation"
                      :key="index"
                      :type="btn.type || 'primary'"
                      size="small"
                      text
                      v-hasPermi="[`${btn.system}`]"
                      @click="btn.clickFun(scope.row)"
                    >
                      {{ btn.name }}
                    </el-button>
                  </template>
                </el-table-column>
              </template>
            </el-table>
            <!-- 分页组件 -->
            <el-pagination
              :total="pagination.total"
              :page-size="pagination.limit"
              :current-page="pagination.page"
              :page-sizes="pagination.pageSizes"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 取消弹窗 -->
    <el-dialog
      v-model="cancelDialogVisible"
      width="500"
      :close-on-click-modal="false"
      align-center
    >
      <template #header>
        <span class="titleRules">*</span>
        <span>取消原因</span>
      </template>
      <el-form
        ref="cancelFormRef"
        style="max-width: 600px"
        :model="cancelForm"
        :rules="cancelRules"
        label-width="auto"
      >
        <el-form-item prop="content">
          <el-input
            v-model="cancelForm.content"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCancel">关闭</el-button>
          <el-button type="primary" @click="submitCancel"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { searchDepyList } from "@/api/recruitment/jobApplication/index.js";
import { seachPersonList } from "@/api/recruitment/needWorkers/index.js";
import {
  onboardingList,
  onboardingcancel,
} from "@/api/employeeRelations/onboarding.js";
import SearchForm from "@/components/searchForm/index.vue";
import { onMounted, reactive, ref, computed, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const emit = defineEmits(["handleAdd", "sizeChange", "currentChange"]);
const router = useRouter();
const { proxy } = getCurrentInstance();
const tabs = reactive([
  {
    label: "预入职",
  },
  {
    label: "入职结束",
  },
]);
// 标签页
const activeName = ref("预入职");
// 查看切换
const tip = ref("预入职");
const tipVal = ref(0);
// 查人
const requireProposerOptions = reactive([]);
// 部门
const buIdOptions = reactive([]);
// 初始搜索表单数据
const initialSearchForm = {
  buId: "",
  jobName: "",
  name: "",
  status: 0,
  pageSize: 10,
  pageNum: 1,
};
const loading = ref(true);
const searchForm = reactive({ ...initialSearchForm });
// 搜索
const formObj = reactive({
  item: [
    {
      input: true,
      label: "",
      prop: "jobName",
      placeholder: "请输入岗位名称",
      disabled: false,
    },
    {
      select: true,
      label: "",
      prop: "buId",
      placeholder: "请选择入职部门",
      disabled: false,
      options: buIdOptions,
    },
    {
      input: true,
      label: "",
      prop: "name",
      placeholder: "请输入姓名",
      disabled: false,
    },
  ],
  btn: [
    {
      type: "primary",
      name: "搜索",
      className: "el-button-primary",
      clickFun: () => {
        handleQuery();
      },
    },
    {
      type: "primary",
      name: "重置",
      className: "el-button-primary",
      clickFun: () => {
        resetTabState();
      },
    },
  ],
});

// 公共column
const onboardingColumn = reactive([
  {
    label: "姓名",
    prop: "name",
    dataType: "text",
  },
  {
    label: "性别",
    prop: "sex",
    dataType: "slot",
    slotName: "sex",
  },
  {
    label: "学历",
    prop: "educationalBackground",
    dataType: "text",
  },
  {
    label: "专业",
    prop: "profession",
    dataType: "text",
  },
  {
    label: "入职部门",
    prop: "deptId",
    dataType: "slot",
    slotName: "deptId",
  },
  {
    label: "岗位名称",
    prop: "applicationPositonName",
    dataType: "text",
  },
  {
    label: "面试通过日",
    prop: "passTime",
    dataType: "text",
  },
  {
    label: "预入职日期",
    prop: "joinTime",
    dataType: "text",
  },
  {
    label: "创建人",
    prop: "createId",
    dataType: "slot",
    slotName: "createId",
  },
  {
    label: "创建时间",
    prop: "createTime",
    dataType: "text",
  },
]);

const column = computed(() => {
  if (tip.value == "预入职") {
    return [
      ...onboardingColumn,
      {
        dataType: "option",
        label: "操作",
        width: "220px",
        operation: [
          {
            name: "查看",
            type: "info",
            icon: "el-icon-edit",
            system: "system:info:entryview",
            clickFun: (row) => {
              return handleInfo(row);
            },
          },
          {
            name: "入职办理",
            type: "success",
            icon: "el-icon-edit",
            system: "system:info:entry",
            clickFun: (row) => {
              return handleOnboarding(row);
            },
          },
          {
            name: "取消",
            type: "warning",
            icon: "el-icon-delete",
            system: "system:info:Resignation",
            clickFun: (row) => {
              return handleCancel(row);
            },
          },
        ],
      },
    ];
  } else if (tip.value == "审批中") {
    return [
      ...onboardingColumn,
      {
        dataType: "option",
        label: "操作",
        width: "200px",
        operation: [
          {
            name: "查看",
            type: "info",
            icon: "el-icon-edit",
            clickFun: (row) => {
              return handleApproveInfo(row);
            },
          },
          {
            name: "审批",
            type: "success",
            icon: "el-icon-edit",
            clickFun: (row) => {
              return handleApprove(row);
            },
          },
        ],
      },
    ];
  } else if (tip.value == "入职结束") {
    return [
      ...onboardingColumn,
      {
        label: "状态",
        prop: "status",
        dataType: "slot",
        slotName: "status",
      },
      {
        dataType: "option",
        label: "操作",
        width: "130px",
        operation: [
          {
            name: "查看",
            type: "info",
            system: "system:info:entryview",
            icon: "el-icon-edit",
            clickFun: (row) => {
              return handleEndInfo(row);
            },
          },
        ],
      },
    ];
  }
});

// 预入职数据
const onboardingTableData = ref([]);
const pagination = ref({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 50],
});
// 取消弹窗
const cancelDialogVisible = ref(false);
const cancelFormRef = ref();
const cancelForm = reactive({
  id: null,
  content: "",
});
const cancelRules = reactive({
  content: [{ required: true, message: "请输入取消原因", trigger: "blur" }],
});

// 重置搜索表单、表格数据和分页信息
const resetTabState = () => {
  searchForm.buId = initialSearchForm.buId;
  searchForm.jobName = initialSearchForm.jobName;
  searchForm.name = initialSearchForm.name;
  searchForm.pageSize = initialSearchForm.pageSize;
  searchForm.pageNum = initialSearchForm.pageNum;
  onboardingTableData.value = [];
  pagination.value = {
    total: 0,
    page: 1,
    limit: 10,
    pageSizes: [10, 20, 30, 50],
  };
  getList();
};

onMounted(() => {
  getDemandDetailsList();
  seachPersonsList();
  getList();
});
const handleQuery = () => {
  getList();
};

// 修改分页处理方法
const handleSizeChange = (newSize) => {
  pagination.value.limit = newSize;
  pagination.value.page = 1;
  getList();
};

const handleCurrentChange = (newPage) => {
  pagination.value.page = newPage;
  getList();
};
// 修改状态显示方法
const formatStatus = (status) => {
  return status === 2 ? "已入职" : status === 5 ? "已取消" : "";
};

// 人
const seachPersonsList = async () => {
  // BMLD
  const res2 = await seachPersonList({
    roleKey: "",
  });
  if (res2.rows.length > 0) {
    res2.rows.map((item) => {
      let label = item.userName;
      let value = item.userId;
      requireProposerOptions.push({
        label,
        value,
      });
    });
  }
};
// 部门
const getDemandDetailsList = async () => {
  // 搜索部门
  const { data } = await searchDepyList();
  if (data.length > 0) {
    data.map((item) => {
      let label = item.deptName;
      let value = item.deptId;
      buIdOptions.push({
        label,
        value,
      });
    });
  }
};
const setDeptName = (deptId) => {
  if (buIdOptions.length > 0) {
    const dept = buIdOptions.find((item) => item.value == deptId);
    return dept ? dept.label : "";
  }
  return "";
};
const setName = (creatId) => {
  if (requireProposerOptions.length > 0) {
    const person = requireProposerOptions.find((item) => item.value == creatId);
    return person ? person.label : "";
  }
  return "";
};
const getList = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchForm,
      status: tipVal.value,
      pageNum: pagination.value.page,
      pageSize: pagination.value.limit,
    };

    const res = await onboardingList(params);

    onboardingTableData.value = res.data?.records || [];
    pagination.value.total = res.data?.total || 0;
  } catch (error) {
    console.error("数据加载失败:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};
// 切换标签页
const handleClick = (tab) => {
  const tipMap = new Map([
    ["预入职", 0],
    ["入职结束", 2],
  ]);
  tip.value = tab.props.name;
  tipVal.value = tipMap.get(tip.value);
  // 重置状态
  resetTabState();
};
// 查看
const handleInfo = (row) => {
  router.push({
    name: "onboardingView",
    query: {
      isApprove: false,
      isApproveBtn: false,
      id: row.id,
    },
  });
};
// 审批查看
const handleApproveInfo = (row) => {
  console.log(row, "查看");
  router.push({
    name: "onboardingView",
    query: {
      isApprove: true,
      isApproveBtn: false,
      id: row.id,
    },
  });
};
// 入职管理 addOnboarding
const handleOnboarding = (row) => {
  console.log("入职管理", row);
  router.push({
    name: "addOnboarding",
    query: {
      id: row.id,
    },
  });
};
// 取消
const handleCancel = (row) => {
  cancelDialogVisible.value = true;
  cancelForm.id = row.id;
};
// 确认/关闭取消
const submitCancel = () => {
  proxy.$refs["cancelFormRef"].validate((valid) => {
    if (valid) {
      const params = {
        id: cancelForm.id,
        content: cancelForm.content,
      };
      onboardingcancel(params).then((res) => {
        if (res.code == 200) {
          cancelDialogVisible.value = false;
          cancelForm.content = "";
          ElMessage.success("取消成功");
          getList();
        } else {
          ElMessage.error("取消失败");
        }
      });
    }
  });
};
const closeCancel = () => {
  cancelDialogVisible.value = false;
  cancelForm.content = "";
};
// 审批
const handleApprove = (row) => {
  console.log(row, "审批");
  router.push({
    name: "onboardingView",
    query: {
      isApprove: true,
      isApproveBtn: true,
    },
  });
};
// 入职结束
const handleEndInfo = (row) => {
  console.log(row, "入职结束");
  router.push({
    name: "onboardingView",
    query: {
      isApprove: true,
      isApproveBtn: false,
      id: row.id,
    },
  });
};
</script>

<style lang="scss" scoped>
//  @import "@/assets/styles/tableAndForm.scss/table.scss";

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.titleRules {
  color: red;
  margin-right: 5px;
}

/* 调整表格样式 */
.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 操作按钮间距 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 保持原有其他样式不变 */
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.titleRules {
  color: red;
  margin-right: 5px;
}
.dept-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
